package classes.io;

import org.junit.Test;

import java.io.*;

/**
 * 字节流转换成字符流，然后再转换成字节流输出。实现编码格式的转换
 */
public class TransStreamTest {
    @Test
    public void test() {
        InputStreamReader inputStreamReader = null;  // 字节流转字符流输入
        OutputStreamWriter outputStreamWriter = null; // 字符流转字节流输出

        BufferedReader bufferedReader = null;
        BufferedWriter bufferedWriter = null;


        try {
            inputStreamReader = new InputStreamReader(new FileInputStream("./src/classes/io/utf8.txt"), "UTF-8"); // 转换成字符流输入
            outputStreamWriter = new OutputStreamWriter(new FileOutputStream("./src/classes/io/gbk.txt"), "GBK"); //转换成字节流输出

            //加一层缓冲流，加速！
            bufferedReader = new BufferedReader(inputStreamReader);
            bufferedWriter = new BufferedWriter(outputStreamWriter);

            String str;
            while ((str = bufferedReader.readLine()) != null) {
                bufferedWriter.write(str);
                bufferedWriter.newLine();
                bufferedWriter.flush(); // 刷新缓存
            }


        } catch (
                IOException e) {
            e.printStackTrace();
        } finally {
            // 关闭最外层的，应该就好了吧？
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            if (bufferedWriter != null) {
                try {
                    bufferedWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
